# -*- coding: utf-8 -*-
from db_conn import *
import io
import time
from datetime import datetime, timedelta
import traceback

date_now = datetime.now()
#date_now = datetime.now() - timedelta(minutes=(gmt_offset_brazil)) #gmtoffset (brazil time)
#out_file_name = date_now.strftime("%d/%m/%Y %H:%M")
out_file_name = "" + date_now.strftime("%Y-%m-%d") + "-export-db"
from_real=0

#@profile
def exportDb(query,filename):    
    cursor,conn = db_connect()
    
    try:
        page_offset = 10000
        cursor.execute('SELECT count(1) FROM `laguardia`.`anatel_import`;')
        total_items = cursor.fetchall()[0][0]
        print "total_items: %s" % (total_items)
        total_pages = (total_items/page_offset)
        total_pages+=1
        print "total_pages: %s" % (total_pages)
            
        #aux_page_step = 0
        file_id = open(filename, "a")
        for aux_page_step in range(total_pages):
            print "aux_page_step: %s" % (aux_page_step)
            str_limit = "LIMIT %s,%s" % (page_offset*aux_page_step,page_offset)
            cursor.execute(query+str_limit)
            resp = cursor.fetchall()
            for row in resp:
                #file_id.write(str("|".join(map(str, row)))+"\n")
                for r in row[:-1]:
                    if not r == None:
                        if str(r) == '0E-8':
                            file_id.write(str("0") + "|")
                        else:
                            file_id.write(str(r) + "|")                        
                    else:
                        file_id.write("|")
                if not row[-1] == None:
                    file_id.write(str(row[-1]))                          
                file_id.write("\n")
                    
        file_id.close()
    except:
        print "Erro ao atualizar o banco"
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                          limit=2, file=sys.stdout)
    finally:
        
        db_disconnect(cursor,conn)


#select_export_id = """
#SELECT CONCAT(`TransmissaoInicial`, '|', `UnidadeFrequenciaTX`, '|', `RecepcaoInicial`, '|', `UnidadeFrequenciaRX`, '|', `Situacao`, '|', `CaraterSecundario`, '|', `IndConfidencial`, '|', `TipoClasseEstacao`, '|', `Horarios`, '|', `DesignacaoEmissao`, '|', `PotenciaOperacao`, '|', `UnidadePotencia`, '|', `Equipamento`, '|', `TipoAntena`, '|', `EquipamentoAntena`, '|', `Ganho`, '|', `FrenteCosta`, '|', `AnguloMeiaPotencia`, '|', `AnguloElevacao`, '|', `Azimute`, '|', `VariacaoAzimutal`, '|', `TipoPolarizacao`, '|', `Altura`, '|', `Raio`, '|', `Latitude`, '|', `Longitude`, '|', `Altitude`, '|', `Estacao`, '|', `Servico`, '|', `Indicativo`, '|', `MedPotenciaMaxima_TR`, '|', `MedLarguraBanda`, '|', `DiametroSGCH`, '|', `Diagrama`, '|', `SiglaEstacao_TRS`, '|', `LongitudeOrbitalSubida`, '|', `NomeFeixeSubida`, '|', `SiglaEstacaoDescida`, '|', `LongitudeOrbitalDescida`, '|', `NomeFeixeDescida`, '|', `TipoEstacao`, '|', `NomeEntidade`, '|', `NumEntidade`, '|', `NomeMunicipio`, '|', `CodMunicipio`, '|', `Endereco`, '|', `UF`, '|', `TipoClasseCorrespondencia`, '|', `Rede`, '|', `Distancia`), `id_antena` FROM `laguardia`.`anatel_import`;
#"""
select_export_id = """  
SELECT `id_antena` 
 FROM `laguardia`.`anatel_import` 
"""
select_export_no_id = """
SELECT `TransmissaoInicial`,
 `UnidadeFrequenciaTX`,
 `RecepcaoInicial`,
 `UnidadeFrequenciaRX`,
 `Situacao`,
 `CaraterSecundario`,
 `IndConfidencial`,
 `TipoClasseEstacao`,
 `Horarios`,
 `DesignacaoEmissao`,
 `PotenciaOperacao`,
 `UnidadePotencia`,
 `Equipamento`,
 `TipoAntena`,
 `EquipamentoAntena`,
 `Ganho`,
 `FrenteCosta`,
 `AnguloMeiaPotencia`,
 `AnguloElevacao`,
 `Azimute`,
 `VariacaoAzimutal`,
 `TipoPolarizacao`,
 `Altura`,
 `Raio`,
 `Latitude`,
 `Longitude`,
 `Altitude`,
 `Estacao`,
 `Servico`,
 `Indicativo`,
 `MedPotenciaMaxima_TR`,
 `MedLarguraBanda`,
 `DiametroSGCH`,
 `Diagrama`,
 `SiglaEstacao_TRS`,
 `LongitudeOrbitalSubida`,
 `NomeFeixeSubida`,
 `SiglaEstacaoDescida`,
 `LongitudeOrbitalDescida`,
 `NomeFeixeDescida`,
 `TipoEstacao`,
 `NomeEntidade`,
 `NumEntidade`,
 `NomeMunicipio`,
 `CodMunicipio`,
 `Endereco`,
 `UF`,
 `TipoClasseCorrespondencia`,
 `Rede`,
 `Distancia`
 FROM `laguardia`.`anatel_import` 
"""

if __name__ == '__main__':
    if not len(sys.argv) < 2:
        
        for v in sys.argv:
            if len(v.split("="))>1:
                param = v.split("=")[0].strip()
                valor = v.split("=")[1].strip()
                try:
                    if param.lower().strip().find("out_file_name")>-1:
                        out_file_name = valor + "-export-db"
                        print "out_file_name: %s" % (out_file_name)                
                    else:
                        eval('%s=%s' % (param,valor))   
                except:
                    exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                    print "%s:%s" % (exceptionType,exceptionValue)
    
    
    start_total = time.time()
    start = time.time()
    exportDb(select_export_no_id,out_file_name+".txt")
    print "(Export sem Id finalizada: %s)" % ((time.time() - start))
    start = time.time() 
    #exportDb(select_export_id,out_file_name+"-id.txt")
    print "(Export com Id finalizada: %s)" % ((time.time() - start))
    print "(Total Tempo Gasto: %s)" % ((time.time() - start_total))
    